{ config, lib, ... }:
with lib;
let
  cfg = config.roles.server.forgejo;
in {
  options.roles.server.forgejo = {
    enable = mkOption {
      default = false;
      type = types.bool;
    };
    domain = mkOption {
      default = config.roles.server.domain;
      type = types.str;
    };
  };

  config = mkIf cfg.enable {
    services = {
      forgejo = {
        enable = true;
        database.type = "postgres";
        settings = {
          mailer.ENABLED = false;
          repository.DEFAULT_BRANCH = "master";
          server = rec {
            DOMAIN = "git." + cfg.domain;
            LANDING_PAGE = "login";
            PROTOCOL = "http+unix";
            ROOT_URL = "https://${DOMAIN}/";
          };
          service.DISABLE_REGISTRATION = true;
          session.COOKIE_SECURE = true;
        };
      };

      nginx = {
        upstreams.forgejo.servers = { "unix:${config.services.forgejo.settings.server.HTTP_ADDR}" = {}; };
        virtualHosts.${config.services.forgejo.settings.server.DOMAIN} = {
          forceSSL = true;
          useACMEHost = cfg.domain;
          locations."/".proxyPass = "http://forgejo";
        };
      };
    };
  };
}
